use corpnum_matched, clear

keep kiprisid CorpNum assg_type

merge 1:n CorpNum using dg_temp.dta
keep if _m == 3
drop _m
ren (loc1 loc2)(dg_loc1 dg_loc2)
merge n:n kiprisid using KIPRIS_cleaned
keep if _m == 3
drop _m

gen loc2_matched = (dg_loc2 == loc2)
gen match_phase = "CorpNum"
qui bysort kiprisid: gen order = _n
qui by kiprisid: egen dup = max(order)

keep kiprisid Symbol loc1 assg_type dup loc2_matched match_phase
order kiprisid Symbol loc1 assg_type dup loc2_matched match_phase
format kipris %15.0g

gsort kiprisid Symbol -loc2_matched
duplicates drop (kiprisid Symbol ), force

qui bysort Symbol: gen order = _n
qui by Symbol: egen dup_symbol = max(order)

drop order dup

qui bysort kiprisid: gen order = _n
qui by kiprisid: egen dup_kip = max(order)

order match_phase kipris Symbol assg_type loc1 loc2_matched dup_kip dup_symbol

gsort match_phase kiprisid Symbol -loc2_matched assg_type

sa corpnum_cleaned, replace
